package com.andatsoft.laisim.asynctask;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;

import com.andatsoft.laisim.activity.MiniPlayerActivity;
import com.andatsoft.laisim.db.DataBaseAccess;
import com.andatsoft.laisim.entity.Song;
import com.andatsoft.laisim.utils.Common;
import com.andatsoft.laisim.utils.Utils;

public class SongScanner extends AsyncTask<String[], Void, Integer[]> {

	private List<String> songAddressList;
	private List<Song> mSongList;
	private Context mContext;
	private boolean mIsFullScan;
	private int mTempFileSize;
	private String[] mExtVals;

	public SongScanner(Context c, boolean isFullScan) {
		this.mContext = c;
		this.mIsFullScan = isFullScan;
		mSongList = new ArrayList<Song>();
		songAddressList = new ArrayList<String>();
	}

	@Override
	protected Integer[] doInBackground(String[]... params) {
		String[] paths = null;
		// scan all
		if (params == null || params.length <= 0) {
			paths = Utils.getAllStoragePath();

		} else {
			paths = params[0];
			if (paths == null)
				paths = Utils.getAllStoragePath();
		}
		SharedPreferences sp = mContext.getSharedPreferences(
				Common.SP_LIB_SETTING_NAME, Context.MODE_PRIVATE);
		mTempFileSize = sp.getInt(Common.SP_LIB_FILE_SIZE, 100) * 1024;

		String valStr = sp.getString(Common.SP_LIB_FILE_EXT, "111000000");
		mExtVals = getSelectedExt(valStr);

		Integer[] re = new Integer[2];
		if (paths != null && paths.length > 0) {
			for (String str : paths) {
				retrieveAllSongs(str);
			}
			updateAllSongInfo();
			re[0] = mSongList.size();

			re[1] = saveSongListToDB(mSongList);
		}
		return re;
	}

	// @Override
	// protected void onPostExecute(Void result) {
	// mSavedFolder = null;
	// songAddressList = null;
	// mSongList = null;
	// }

	private List<String> retrieveAllSongs(String songFolder) {
		File file = new File(songFolder);
		file.listFiles(new FileFilter() {

			@Override
			public boolean accept(File name) {
				if (name.isDirectory() && !name.isHidden()) {
					songAddressList = retrieveAllSongs(name.getAbsolutePath());
				}
				if (name.length() < mTempFileSize)
					return false;
				String filename = name.getAbsolutePath().toLowerCase(Locale.US);
				if (isMusicFileAccepted(filename)) {
					songAddressList.add(name.getAbsolutePath());
					return true;
				}
				// if (filename.endsWith(".flac")) {
				//
				//
				// return true;
				//
				// } else if (filename.endsWith(".mp3")
				// || filename.endsWith(".wav")) {
				// songAddressList.add(name.getAbsolutePath());
				// // Log.d("Song", name.getAbsolutePath());
				// return true;
				// }
				return false;
			}
		});
		return songAddressList;
	}

	private boolean isMusicFileAccepted(String name) {
		for (String ext : mExtVals) {
			if (name.endsWith(ext))
				return true;
		}
		return false;
	}

	private void updateAllSongInfo() {
		for (String str : songAddressList) {
			Song song = new Song(mContext, str);
			song.updateSongInfo(mContext);
			mSongList.add(song);
		}
	}

	/**
	 * @param l
	 * @return The number of actual song added to the database
	 */
	private int saveSongListToDB(List<Song> l) {
		DataBaseAccess db = DataBaseAccess.getInstance(mContext
				.getApplicationContext());
		if (mIsFullScan) {
			// drop all table
			db.upgradeWhenDoFullScan();
		}
		int count = 0;
		for (Song s : l) {
			if (db.addSong(s))
				count++;
		}
		l = db.getAllSong();
		db.savePlayingSong(l);
		return count;
	}

	private String[] getSelectedExt(String src) {
		List<String> tempVal = new ArrayList<String>();
		for (int i = 0; i < src.length(); i++) {
			int val = src.charAt(i) - 48;
			if (val == 0)
				continue;

			switch (i) {
			case 0:// mp3
				tempVal.add("mp3");
				break;
			case 1:// flac
					// .flac file only supported from android 3.1+
				if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR1)
					tempVal.add("flac");
				break;
			case 2:// wav
				tempVal.add("wav");
				break;
			case 3:// mp4
				tempVal.add("mp4");
				break;
			case 4:// m4a
				tempVal.add("m4a");
				break;
			case 5:// aac
				tempVal.add("aac");
				break;
			case 6:// ogg
				tempVal.add("ogg");
				break;
			case 7:// mid
				tempVal.add("mid");
				break;
			case 8:// 3gp
				tempVal.add("3gp");
				break;
			}
		}
		return tempVal.toArray(new String[tempVal.size()]);
	}

}
